#!/usr/bin/bash

BASE_DIR=`pwd`
LOCAL=/usr/local/bin

read_ini(){
  echo `awk -F '=' -v key="$1" '$1==key {print $2}' $BASE_DIR/conf/deploy.ini`
}

make_python(){
  version=`read_ini python_version`
  priority=`read_ini python_priority`
  git clone --depth 1 -b $version https://gitee.com/mirrors/cpython.git /opt/cpython
  cd /opt/cpython
  ./configure --enable-optimizations
  make -j 8
  make altinstall
  update-alternatives --install /usr/bin/python python /usr/local/bin/python$version $priority
  cd ${BASE_DIR}
}

make_depends(){
  apt update
  apt upgrade -y
  apt install -y `cat $BASE_DIR/conf/apts.txt`
}

make_pip(){
    python_version=`read_ini python_version`
    pip_source=`read_ini pip_source`
    $LOCAL/python$python_version -m get-pip
    $LOCAL/pip$python_version config set global.index-url $pip_source
}

make_docker_ce(){
    curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" \
        | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt update
    apt install docker-ce docker-ce-cli container.io -y
    mkdir -p /etc/docker && touch /etc/docker/daemon.json
    docker_source=`read_ini docker_source`
    echo {\"registry-mirrors\":[\"$docker_source\"]} >> /etc/docker/daemon.json
}


make_nodejs(){
  curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
  apt install -y nodejs
  npm config set registry https://registry.npm.taobao.org
}

case $1 in
  all)
    make_depends
    make_python
    make_pip
    ;;
  depends)
    make_depends
    ;;
  python)
    make_python
    ;;
  pip)
    make_pip
    ;;
  node)
    make_nodejs
    ;;
esac
